<!DOCTYPE html>
<html lang="zh-CN">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>三人摸牌 - 纸牌游戏</title>
  <!-- Tailwind CSS v3 -->
  <script src="https://cdn.tailwindcss.com"></script>
  <!-- Font Awesome -->
  <link href="https://cdn.jsdelivr.net/npm/font-awesome@4.7.0/css/font-awesome.min.css" rel="stylesheet">
  
  <script>
    tailwind.config = {
      theme: {
        extend: {
          colors: {
            primary: '#1a365d',
            secondary: '#2b6cb0',
            accent: '#ecc94b',
            danger: '#e53e3e',
            dark: '#0f172a',
            light: '#e2e8f0'
          },
          fontFamily: {
            sans: ['Inter', 'system-ui', 'sans-serif'],
          },
          animation: {
            'deal-card': 'dealCard 0.5s ease-out forwards',
            'flip-card': 'flipCard 0.6s ease-out forwards',
            'pulse-win': 'pulseWin 1.5s infinite',
          },
          keyframes: {
            dealCard: {
              '0%': { transform: 'translateY(-500px) rotate(-20deg)', opacity: 0 },
              '100%': { transform: 'translateY(0) rotate(0)', opacity: 1 },
            },
            flipCard: {
              '0%': { transform: 'rotateY(0deg)' },
              '100%': { transform: 'rotateY(180deg)' },
            },
            pulseWin: {
              '0%, 100%': { boxShadow: '0 0 0 0 rgba(236, 201, 75, 0.7)' },
              '50%': { boxShadow: '0 0 20px 5px rgba(236, 201, 75, 0.7)' },
            }
          }
        }
      }
    }
  </script>
  <style type="text/tailwindcss">
    @layer utilities {
      .card {
        @apply w-20 h-28 md:w-24 md:h-34 bg-white rounded-lg shadow-lg overflow-hidden relative transform transition-all duration-300;
      }
      .card-back {
        @apply bg-cover bg-center;
        background-image: url('https://p11-doubao-search-sign.byteimg.com/pgc-image/78525156921c45969814000864912728~tplv-be4g95zd3a-image.jpeg?rk3s=1388297f&x-expires=1765011356&x-signature=9V2M6F93Qd%2FqXh20%2B%2B70a%2B9g6E%3D');
      }
      .card-front {
        @apply absolute inset-0 bg-white flex flex-col items-center justify-center p-1 transform rotateY-180;
      }
      .card-rank {
        @apply text-2xl font-bold;
      }
      .card-suit {
        @apply text-3xl mt-1;
      }
      .suit-heart, .suit-diamond {
        @apply text-red-500;
      }
      .suit-club, .suit-spade {
        @apply text-black;
      }
      .player-card-slot {
        @apply w-16 h-24 md:w-20 md:h-28 border-2 border-dashed border-gray-400 rounded-lg flex items-center justify-center;
      }
      .highlight-winner {
        @apply ring-4 ring-accent ring-opacity-75 animate-pulse-win;
      }
      .glass-effect {
        @apply bg-white bg-opacity-10 backdrop-blur-md rounded-xl border border-white border-opacity-20;
      }
      .btn-primary {
        @apply bg-primary hover:bg-opacity-80 text-white font-bold py-2 px-4 rounded-lg transition-all duration-300 transform hover:scale-105 focus:outline-none focus:ring-2 focus:ring-accent focus:ring-opacity-50;
      }
      .btn-secondary {
        @apply bg-secondary hover:bg-opacity-80 text-white font-bold py-2 px-4 rounded-lg transition-all duration-300 transform hover:scale-105 focus:outline-none focus:ring-2 focus:ring-accent focus:ring-opacity-50;
      }
      .btn-accent {
        @apply bg-accent hover:bg-opacity-80 text-primary font-bold py-2 px-4 rounded-lg transition-all duration-300 transform hover:scale-105 focus:outline-none focus:ring-2 focus:ring-primary focus:ring-opacity-50;
      }
      .btn-danger {
        @apply bg-danger hover:bg-opacity-80 text-white font-bold py-2 px-4 rounded-lg transition-all duration-300 transform hover:scale-105 focus:outline-none focus:ring-2 focus:ring-white focus:ring-opacity-50;
      }
      .input-primary {
        @apply bg-white bg-opacity-10 border border-white border-opacity-20 rounded-lg px-4 py-2 text-white placeholder-gray-300 focus:outline-none focus:ring-2 focus:ring-accent focus:ring-opacity-50;
      }
    }
  </style>
</head>
<body class="bg-gradient-to-br from-dark to-primary min-h-screen text-light">
  <!-- 游戏容器 -->
  <div id="game-container" class="container mx-auto px-4 py-8 max-w-6xl">
    <!-- 登录界面 -->
    <div id="login-screen" class="flex flex-col items-center justify-center min-h-[80vh]">
      <img src="https://p3-flow-imagex-sign.byteimg.com/tos-cn-i-a9rns2rl98/rc/pc/super_tool/c848ddcaf67049f8bb6a958ab93fe29c~tplv-a9rns2rl98-image.image?rcl=2025110616551961168E618163CC04829F&rk3s=8e244e95&rrcfp=f06b921b&x-expires=1765011375&x-signature=pd7oMMlzRZCa0W2nj8UOAenhTgw%3D" alt="三人摸牌" class="w-48 h-48 mb-8">
      <h1 class="text-4xl md:text-5xl font-bold mb-8 text-center">三人摸牌</h1>
      
      <div class="glass-effect p-8 w-full max-w-md">
        <div class="mb-6">
          <label for="player-name" class="block mb-2 text-sm font-medium">昵称</label>
          <input type="text" id="player-name" class="input-primary w-full" placeholder="请输入您的昵称" required>
        </div>
        
        <div class="mb-6">
          <label class="block mb-2 text-sm font-medium">选择头像</label>
          <div class="grid grid-cols-4 gap-3">
            <div class="avatar-option selected">
              <img src="https://p26-doubao-search-sign.byteimg.com/mosaic-legacy/bdb0001864252078340~tplv-be4g95zd3a-image.jpeg?rk3s=1388297f&x-expires=1765011357&x-signature=8JwTk3QmN%2BC2Iu18zGd83a0O59c%3D" alt="头像1" class="w-12 h-12 rounded-full cursor-pointer border-2 border-accent">
            </div>
            <div class="avatar-option">
              <img src="https://p3-doubao-search-sign.byteimg.com/mosaic-legacy/bdb0001864252078341~tplv-be4g95zd3a-image.jpeg?rk3s=1388297f&x-expires=1765011357&x-signature=7HCRLWAobymB9mZ5t3vN8YrXkE4%3D" alt="头像2" class="w-12 h-12 rounded-full cursor-pointer border-2 border-transparent">
            </div>
            <div class="avatar-option">
              <img src="https://p3-doubao-search-sign.byteimg.com/mosaic-legacy/bdb0001864252078342~tplv-be4g95zd3a-image.jpeg?rk3s=1388297f&x-expires=1765011357&x-signature=k3H%2F8I7G9F3D2S1A4Q5W6E8R9T%3D" alt="头像3" class="w-12 h-12 rounded-full cursor-pointer border-2 border-transparent">
            </div>
            <div class="avatar-option">
              <img src="https://p3-doubao-search-sign.byteimg.com/pgc-image/3732999201414056124521~tplv-be4g95zd3a-image.jpeg?rk3s=1388297f&x-expires=1765011357&x-signature=6G5F4D3S2A1Q8W7E9R6T5Y4U%3D" alt="头像4" class="w-12 h-12 rounded-full cursor-pointer border-2 border-transparent">
            </div>
          </div>
        </div>
        
        <button id="login-btn" class="btn-primary w-full">进入游戏</button>
      </div>
    </div>
    
    <!-- 房间列表界面 -->
    <div id="room-list-screen" class="hidden">
      <div class="flex justify-between items-center mb-6">
        <h2 class="text-3xl font-bold">游戏房间</h2>
        <div class="flex items-center">
          <span id="player-info" class="mr-4">
            <img id="player-avatar-small" src="https://p26-doubao-search-sign.byteimg.com/mosaic-legacy/bdb0001864252078340~tplv-be4g95zd3a-image.jpeg?rk3s=1388297f&x-expires=1765011357&x-signature=8JwTk3QmN%2BC2Iu18zGd83a0O59c%3D" alt="玩家头像" class="w-8 h-8 rounded-full inline-block mr-2">
            <span id="player-name-display">玩家</span>
          </span>
          <button id="logout-btn" class="btn-secondary">退出</button>
        </div>
      </div>
      
      <div class="glass-effect p-6 mb-6">
        <div class="flex justify-between items-center mb-4">
          <h3 class="text-xl font-semibold">创建房间</h3>
        </div>
        <div class="flex flex-col md:flex-row gap-4">
          <input type="text" id="room-name" class="input-primary flex-grow" placeholder="房间名称">
          <button id="create-room-btn" class="btn-accent whitespace-nowrap">创建房间</button>
        </div>
      </div>
      
      <div class="glass-effect p-6">
        <h3 class="text-xl font-semibold mb-4">可加入房间</h3>
        <div id="room-list" class="space-y-3">
          <!-- 房间列表将通过JavaScript动态生成 -->
        </div>
      </div>
    </div>
    
    <!-- 游戏房间界面 -->
    <div id="game-room-screen" class="hidden">
      <div class="flex justify-between items-center mb-4">
        <div>
          <h2 class="text-3xl font-bold">房间: <span id="current-room-name">未命名房间</span></h2>
          <p class="text-sm text-gray-300">房间号: <span id="current-room-id">0000</span></p>
        </div>
        <div class="flex items-center">
          <span id="game-player-info" class="mr-4">
            <img id="game-player-avatar-small" src="https://p26-doubao-search-sign.byteimg.com/mosaic-legacy/bdb0001864252078340~tplv-be4g95zd3a-image.jpeg?rk3s=1388297f&x-expires=1765011357&x-signature=8JwTk3QmN%2BC2Iu18zGd83a0O59c%3D" alt="玩家头像" class="w-8 h-8 rounded-full inline-block mr-2">
            <span id="game-player-name-display">玩家</span>
          </span>
          <button id="leave-room-btn" class="btn-secondary">离开房间</button>
        </div>
      </div>
      
      <!-- 游戏状态信息 -->
      <div class="glass-effect p-4 mb-6">
        <div class="flex flex-wrap justify-between items-center">
          <div>
            <span class="text-sm text-gray-300">游戏状态:</span>
            <span id="game-status" class="ml-2 font-medium">等待玩家加入</span>
          </div>
          <div>
            <span class="text-sm text-gray-300">当前玩家:</span>
            <span id="current-player-count" class="ml-2 font-medium">1/4</span>
          </div>
          <div>
            <span class="text-sm text-gray-300">轮到:</span>
            <span id="current-turn" class="ml-2 font-medium">无</span>
          </div>
          <div>
            <span class="text-sm text-gray-300">奖池:</span>
            <span id="pot-amount" class="ml-2 font-medium text-accent">0  chips</span>
          </div>
        </div>
      </div>
      
      <!-- 游戏区域 -->
      <div class="relative mb-6">
        <div class="w-full h-64 md:h-80 bg-cover bg-center rounded-xl" style="background-image: url('https://p3-doubao-search-sign.byteimg.com/pgc-image/2021031216165913993391~tplv-be4g95zd3a-image.jpeg?rk3s=1388297f&x-expires=1765011358&x-signature=0gDYt%2Bs8T7e6H5j4K3l2M1N0P9%3D');">
          <!-- 牌堆 -->
          <div id="deck" class="absolute top-4 left-4 flex flex-col items-center">
            <div class="card card-back mb-2"></div>
            <span class="text-xs bg-black bg-opacity-50 px-2 py-1 rounded">牌堆</span>
          </div>
          
          <!-- 玩家区域 -->
          <div class="players-container">
            <!-- 左侧玩家 -->
            <div id="player-left" class="absolute top-1/2 left-4 transform -translate-y-1/2 flex flex-col items-center">
              <div class="flex items-center mb-2">
                <img class="player-avatar w-10 h-10 rounded-full mr-2" src="https://p3-doubao-search-sign.byteimg.com/mosaic-legacy/bdb0001864252078341~tplv-be4g95zd3a-image.jpeg?rk3s=1388297f&x-expires=1765011357&x-signature=7HCRLWAobymB9mZ5t3vN8YrXkE4%3D" alt="玩家头像">
                <div>
                  <div class="player-name text-sm font-medium">玩家2</div>
                  <div class="player-chips text-xs text-accent">1000 chips</div>
                </div>
              </div>
              <div class="player-cards flex gap-2">
                <div class="card card-back"></div>
                <div class="card card-back"></div>
                <div class="card card-back"></div>
              </div>
              <div class="player-status mt-2 text-xs bg-black bg-opacity-50 px-2 py-1 rounded">准备中</div>
            </div>
            
            <!-- 右侧玩家 -->
            <div id="player-right" class="absolute top-1/2 right-4 transform -translate-y-1/2 flex flex-col items-center">
              <div class="flex items-center mb-2">
                <img class="player-avatar w-10 h-10 rounded-full mr-2" src="https://p3-doubao-search-sign.byteimg.com/mosaic-legacy/bdb0001864252078342~tplv-be4g95zd3a-image.jpeg?rk3s=1388297f&x-expires=1765011357&x-signature=k3H%2F8I7G9F3D2S1A4Q5W6E8R9T%3D" alt="玩家头像">
                <div>
                  <div class="player-name text-sm font-medium">玩家3</div>
                  <div class="player-chips text-xs text-accent">1000 chips</div>
                </div>
              </div>
              <div class="player-cards flex gap-2">
                <div class="card card-back"></div>
                <div class="card card-back"></div>
                <div class="card card-back"></div>
              </div>
              <div class="player-status mt-2 text-xs bg-black bg-opacity-50 px-2 py-1 rounded">准备中</div>
            </div>
            
            <!-- 上方玩家 -->
            <div id="player-top" class="absolute top-4 left-1/2 transform -translate-x-1/2 flex flex-col items-center">
              <div class="flex items-center mb-2">
                <img class="player-avatar w-10 h-10 rounded-full mr-2" src="https://p3-doubao-search-sign.byteimg.com/pgc-image/3732999201414056124521~tplv-be4g95zd3a-image.jpeg?rk3s=1388297f&x-expires=1765011357&x-signature=6G5F4D3S2A1Q8W7E9R6T5Y4U%3D" alt="玩家头像">
                <div>
                  <div class="player-name text-sm font-medium">玩家4</div>
                  <div class="player-chips text-xs text-accent">1000 chips</div>
                </div>
              </div>
              <div class="player-cards flex gap-2">
                <div class="card card-back"></div>
                <div class="card card-back"></div>
                <div class="card card-back"></div>
              </div>
              <div class="player-status mt-2 text-xs bg-black bg-opacity-50 px-2 py-1 rounded">准备中</div>
            </div>
            
            <!-- 自己（下方玩家） -->
            <div id="player-self" class="absolute bottom-4 left-1/2 transform -translate-x-1/2 flex flex-col items-center">
              <div class="flex items-center mb-2">
                <img id="self-avatar" class="player-avatar w-10 h-10 rounded-full mr-2" src="https://p26-doubao-search-sign.byteimg.com/mosaic-legacy/bdb0001864252078340~tplv-be4g95zd3a-image.jpeg?rk3s=1388297f&x-expires=1765011357&x-signature=8JwTk3QmN%2BC2Iu18zGd83a0O59c%3D" alt="玩家头像">
                <div>
                  <div id="self-name" class="player-name text-sm font-medium">你</div>
                  <div id="self-chips" class="player-chips text-xs text-accent">1000 chips</div>
                </div>
              </div>
              <div id="self-cards" class="player-cards flex gap-2">
                <div class="player-card-slot"></div>
                <div class="player-card-slot"></div>
                <div class="player-card-slot"></div>
              </div>
              <div id="self-status" class="mt-2 text-xs bg-black bg-opacity-50 px-2 py-1 rounded">准备中</div>
            </div>
          </div>
        </div>
      </div>
      
      <!-- 游戏控制区 -->
      <div class="glass-effect p-6 mb-6">
        <div class="flex flex-wrap gap-4 justify-center mb-6">
          <button id="ready-btn" class="btn-accent">准备</button>
          <button id="fold-btn" class="btn-danger" disabled>弃牌</button>
          <button id="check-btn" class="btn-secondary" disabled>过牌</button>
          <div class="flex items-center">
            <button id="bet-minus" class="btn-secondary px-2" disabled>-</button>
            <input type="number" id="bet-amount" class="input-primary mx-2 w-20 text-center" value="10" min="10" disabled>
            <button id="bet-plus" class="btn-secondary px-2" disabled>+</button>
            <button id="bet-btn" class="btn-primary ml-2" disabled>下注</button>
          </div>
        </div>
        
        <div class="text-center">
          <div id="game-message" class="text-lg font-medium mb-2">等待其他玩家准备...</div>
          <div id="hand-rank" class="text-sm text-gray-300">你的牌型: -</div>
        </div>
      </div>
      
      <!-- 聊天区域 -->
      <div class="glass-effect p-6">
        <h3 class="text-xl font-semibold mb-4">聊天</h3>
        <div id="chat-messages" class="h-40 overflow-y-auto mb-4 space-y-2">
          <!-- 聊天消息将通过JavaScript动态生成 -->
        </div>
        <div class="flex">
          <input type="text" id="chat-input" class="input-primary flex-grow mr-2" placeholder="输入消息...">
          <button id="send-chat-btn" class="btn-secondary">发送</button>
        </div>
      </div>
    </div>
    
    <!-- 游戏结果弹窗 -->
    <div id="result-modal" class="fixed inset-0 bg-black bg-opacity-75 flex items-center justify-center z-50 hidden">
      <div class="glass-effect p-8 max-w-md w-full">
        <h3 class="text-2xl font-bold mb-6 text-center">游戏结束</h3>
        
        <div id="result-content" class="space-y-4 mb-6">
          <!-- 结果内容将通过JavaScript动态生成 -->
        </div>
        
        <div class="flex justify-center">
          <button id="new-game-btn" class="btn-accent">再来一局</button>
        </div>
      </div>
    </div>
  </div>

  <script>
    // 游戏数据
    const gameData = {
      player: {
        id: 'player-' + Math.floor(Math.random() * 10000),
        name: '玩家',
        avatar: 'https://p26-doubao-search-sign.byteimg.com/mosaic-legacy/bdb0001864252078340~tplv-be4g95zd3a-image.jpeg?rk3s=1388297f&x-expires=1765011357&x-signature=8JwTk3QmN%2BC2Iu18zGd83a0O59c%3D',
        chips: 1000,
        cards: [],
        status: 'waiting', // waiting, ready, playing, folded
        handRank: null
      },
      rooms: [
        {
          id: 'room-1',
          name: '新手房间',
          players: [
            {
              id: 'player-1',
              name: '玩家1',
              avatar: 'https://p26-doubao-search-sign.byteimg.com/mosaic-legacy/bdb0001864252078340~tplv-be4g95zd3a-image.jpeg?rk3s=1388297f&x-expires=1765011357&x-signature=8JwTk3QmN%2BC2Iu18zGd83a0O59c%3D',
              chips: 1000,
              status: 'ready'
            }
          ],
          status: 'waiting', // waiting, playing
          pot: 0,
          currentTurn: 0,
          deck: []
        },
        {
          id: 'room-2',
          name: '高手房间',
          players: [
            {
              id: 'player-2',
              name: '玩家2',
              avatar: 'https://p3-doubao-search-sign.byteimg.com/mosaic-legacy/bdb0001864252078341~tplv-be4g95zd3a-image.jpeg?rk3s=1388297f&x-expires=1765011357&x-signature=7HCRLWAobymB9mZ5t3vN8YrXkE4%3D',
              chips: 1000,
              status: 'ready'
            },
            {
              id: 'player-3',
              name: '玩家3',
              avatar: 'https://p3-doubao-search-sign.byteimg.com/mosaic-legacy/bdb0001864252078342~tplv-be4g95zd3a-image.jpeg?rk3s=1388297f&x-expires=1765011357&x-signature=k3H%2F8I7G9F3D2S1A4Q5W6E8R9T%3D',
              chips: 1000,
              status: 'ready'
            }
          ],
          status: 'waiting',
          pot: 0,
          currentTurn: 0,
          deck: []
        }
      ],
      currentRoom: null,
      chatMessages: []
    };
    
    // 卡牌数据
    const suits = ['♥', '♦', '♣', '♠'];
    const ranks = ['A', '2', '3', '4', '5', '6', '7', '8', '9', '10', 'J', 'Q', 'K'];
    const cardValues = {
      '2': 2, '3': 3, '4': 4, '5': 5, '6': 6, '7': 7, '8': 8, '9': 9, '10': 10,
      'J': 11, 'Q': 12, 'K': 13, 'A': 14
    };
    const handRanks = [
      { name: '豹子', value: 7 },
      { name: '顺金', value: 6 },
      { name: '金花', value: 5 },
      { name: '顺子', value: 4 },
      { name: '对子', value: 3 },
      { name: '单张', value: 2 },
      { name: '高牌', value: 1 }
    ];
    
    // DOM元素
    const loginScreen = document.getElementById('login-screen');
    const roomListScreen = document.getElementById('room-list-screen');
    const gameRoomScreen = document.getElementById('game-room-screen');
    const resultModal = document.getElementById('result-modal');
    
    // 登录界面元素
    const playerNameInput = document.getElementById('player-name');
    const avatarOptions = document.querySelectorAll('.avatar-option');
    const loginBtn = document.getElementById('login-btn');
    
    // 房间列表界面元素
    const playerInfo = document.getElementById('player-info');
    const playerAvatarSmall = document.getElementById('player-avatar-small');
    const playerNameDisplay = document.getElementById('player-name-display');
    const logoutBtn = document.getElementById('logout-btn');
    const roomNameInput = document.getElementById('room-name');
    const createRoomBtn = document.getElementById('create-room-btn');
    const roomList = document.getElementById('room-list');
    
    // 游戏房间界面元素
    const currentRoomName = document.getElementById('current-room-name');
    const currentRoomId = document.getElementById('current-room-id');
    const gamePlayerInfo = document.getElementById('game-player-info');
    const gamePlayerAvatarSmall = document.getElementById('game-player-avatar-small');
    const gamePlayerNameDisplay = document.getElementById('game-player-name-display');
    const leaveRoomBtn = document.getElementById('leave-room-btn');
    const gameStatus = document.getElementById('game-status');
    const currentPlayerCount = document.getElementById('current-player-count');
    const currentTurn = document.getElementById('current-turn');
    const potAmount = document.getElementById('pot-amount');
    const selfAvatar = document.getElementById('self-avatar');
    const selfName = document.getElementById('self-name');
    const selfChips = document.getElementById('self-chips');
    const selfCards = document.getElementById('self-cards');
    const selfStatus = document.getElementById('self-status');
    const readyBtn = document.getElementById('ready-btn');
    const foldBtn = document.getElementById('fold-btn');
    const checkBtn = document.getElementById('check-btn');
    const betMinus = document.getElementById('bet-minus');
    const betPlus = document.getElementById('bet-plus');
    const betAmount = document.getElementById('bet-amount');
    const betBtn = document.getElementById('bet-btn');
    const gameMessage = document.getElementById('game-message');
    const handRank = document.getElementById('hand-rank');
    const chatMessages = document.getElementById('chat-messages');
    const chatInput = document.getElementById('chat-input');
    const sendChatBtn = document.getElementById('send-chat-btn');
    
    // 结果弹窗元素
    const resultContent = document.getElementById('result-content');
    const newGameBtn = document.getElementById('new-game-btn');
    
    // 初始化
    function init() {
      // 绑定事件
      bindEvents();
      
      // 初始化房间列表
      updateRoomList();
    }
    
    // 绑定事件
    function bindEvents() {
      // 登录界面事件
      avatarOptions.forEach(option => {
        option.addEventListener('click', () => {
          avatarOptions.forEach(opt => opt.querySelector('img').classList.remove('border-accent'));
          avatarOptions.forEach(opt => opt.querySelector('img').classList.add('border-transparent'));
          option.querySelector('img').classList.remove('border-transparent');
          option.querySelector('img').classList.add('border-accent');
          gameData.player.avatar = option.querySelector('img').src;
        });
      });
      
      loginBtn.addEventListener('click', login);
      
      // 房间列表界面事件
      logoutBtn.addEventListener('click', logout);
      createRoomBtn.addEventListener('click', createRoom);
      
      // 游戏房间界面事件
      leaveRoomBtn.addEventListener('click', leaveRoom);
      readyBtn.addEventListener('click', toggleReady);
      foldBtn.addEventListener('click', fold);
      checkBtn.addEventListener('click', check);
      betMinus.addEventListener('click', () => changeBetAmount(-10));
      betPlus.addEventListener('click', () => changeBetAmount(10));
      betBtn.addEventListener('click', bet);
      sendChatBtn.addEventListener('click', sendChat);
      chatInput.addEventListener('keypress', (e) => {
        if (e.key === 'Enter') sendChat();
      });
      
      // 结果弹窗事件
      newGameBtn.addEventListener('click', startNewGame);
    }
    
    // 登录
    function login() {
      const name = playerNameInput.value.trim();
      if (!name) {
        alert('请输入昵称');
        return;
      }
      
      gameData.player.name = name;
      
      // 更新玩家信息显示
      playerAvatarSmall.src = gameData.player.avatar;
      playerNameDisplay.textContent = gameData.player.name;
      gamePlayerAvatarSmall.src = gameData.player.avatar;
      gamePlayerNameDisplay.textContent = gameData.player.name;
      selfAvatar.src = gameData.player.avatar;
      selfName.textContent = '你 (' + gameData.player.name + ')';
      
      // 切换到房间列表界面
      loginScreen.classList.add('hidden');
      roomListScreen.classList.remove('hidden');
    }
    
    // 登出
    function logout() {
      // 重置玩家信息
      gameData.player.name = '玩家';
      gameData.player.avatar = 'https://p26-doubao-search-sign.byteimg.com/mosaic-legacy/bdb0001864252078340~tplv-be4g95zd3a-image.jpeg?rk3s=1388297f&x-expires=1765011357&x-signature=8JwTk3QmN%2BC2Iu18zGd83a0O59c%3D';
      playerNameInput.value = '';
      
      // 重置头像选择
      avatarOptions.forEach(opt => opt.querySelector('img').classList.remove('border-accent'));
      avatarOptions.forEach(opt => opt.querySelector('img').classList.add('border-transparent'));
      avatarOptions[0].querySelector('img').classList.remove('border-transparent');
      avatarOptions[0].querySelector('img').classList.add('border-accent');
      
      // 切换到登录界面
      roomListScreen.classList.add('hidden');
      gameRoomScreen.classList.add('hidden');
      loginScreen.classList.remove('hidden');
    }
    
    // 创建房间
    function createRoom() {
      const name = roomNameInput.value.trim() || '未命名房间';
      
      const newRoom = {
        id: 'room-' + Date.now(),
        name: name,
        players: [
          {
            id: gameData.player.id,
            name: gameData.player.name,
            avatar: gameData.player.avatar,
            chips: 1000,
            status: 'waiting'
          }
        ],
        status: 'waiting',
        pot: 0,
        currentTurn: 0,
        deck: []
      };
      
      gameData.rooms.push(newRoom);
      gameData.currentRoom = newRoom;
      
      // 更新房间列表
      updateRoomList();
      
      // 进入游戏房间
      enterGameRoom();
    }
    
    // 更新房间列表
    function updateRoomList() {
      roomList.innerHTML = '';
      
      if (gameData.rooms.length === 0) {
        roomList.innerHTML = '<p class="text-gray-400 text-center py-4">暂无房间，请创建新房间</p>';
        return;
      }
      
      gameData.rooms.forEach(room => {
        if (room.players.length >= 4) return;
        
        const roomElement = document.createElement('div');
        roomElement.className = 'glass-effect p-4 flex justify-between items-center cursor-pointer hover:bg-white hover:bg-opacity-5 transition-all';
        roomElement.innerHTML = `
          <div>
            <h4 class="font-medium">${room.name}</h4>
            <p class="text-xs text-gray-400">房间号: ${room.id}</p>
          </div>
          <div class="flex items-center">
            <span class="text-xs bg-accent bg-opacity-20 text-accent px-2 py-1 rounded mr-2">${room.players.length}/4</span>
            <span class="text-xs">${room.status === 'waiting' ? '等待中' : '游戏中'}</span>
          </div>
        `;
        
        roomElement.addEventListener('click', () => {
          // 检查房间是否已满
          if (room.players.length >= 4) {
            alert('房间已满');
            return;
          }
          
          // 检查玩家是否已在房间中
          const isInRoom = room.players.some(p => p.id === gameData.player.id);
          if (!isInRoom) {
            room.players.push({
              id: gameData.player.id,
              name: gameData.player.name,
              avatar: gameData.player.avatar,
              chips: 1000,
              status: 'waiting'
            });
          }
          
          gameData.currentRoom = room;
          enterGameRoom();
        });
        
        roomList.appendChild(roomElement);
      });
    }
    
    // 进入游戏房间
    function enterGameRoom() {
      // 更新房间信息
      currentRoomName.textContent = gameData.currentRoom.name;
      currentRoomId.textContent = gameData.currentRoom.id;
      
      // 更新玩家信息
      selfChips.textContent = gameData.player.chips + ' chips';
      selfStatus.textContent = '准备中';
      
      // 重置游戏状态
      gameStatus.textContent = '等待玩家加入';
      currentPlayerCount.textContent = gameData.currentRoom.players.length + '/4';
      currentTurn.textContent = '无';
      potAmount.textContent = '0 chips';
      gameMessage.textContent = '等待其他玩家准备...';
      handRank.textContent = '你的牌型: -';
      
      // 清空聊天记录
      chatMessages.innerHTML = '';
      gameData.chatMessages = [];
      
      // 重置自己的牌
      selfCards.innerHTML = `
        <div class="player-card-slot"></div>
        <div class="player-card-slot"></div>
        <div class="player-card-slot"></div>
      `;
      
      // 重置其他玩家的牌
      document.querySelectorAll('.player-cards').forEach(cards => {
        if (cards.id !== 'self-cards') {
          cards.innerHTML = `
            <div class="card card-back"></div>
            <div class="card card-back"></div>
            <div class="card card-back"></div>
          `;
        }
      });
      
      // 重置按钮状态
      readyBtn.textContent = '准备';
      readyBtn.classList.remove('btn-danger');
      readyBtn.classList.add('btn-accent');
      foldBtn.disabled = true;
      checkBtn.disabled = true;
      betMinus.disabled = true;
      betPlus.disabled = true;
      betAmount.disabled = true;
      betBtn.disabled = true;
      
      // 切换到游戏房间界面
      roomListScreen.classList.add('hidden');
      gameRoomScreen.classList.remove('hidden');
      
      // 更新其他玩家信息
      updateOtherPlayers();
      
      // 模拟其他玩家加入
      setTimeout(simulatePlayersJoining, 2000);
    }
    
    // 离开房间
    function leaveRoom() {
      if (!gameData.currentRoom) return;
      
      // 从房间中移除玩家
      gameData.currentRoom.players = gameData.currentRoom.players.filter(p => p.id !== gameData.player.id);
      
      // 如果房间为空，删除房间
      if (gameData.currentRoom.players.length === 0) {
        gameData.rooms = gameData.rooms.filter(r => r.id !== gameData.currentRoom.id);
      }
      
      gameData.currentRoom = null;
      
      // 更新房间列表
      updateRoomList();
      
      // 切换到房间列表界面
      gameRoomScreen.classList.add('hidden');
      roomListScreen.classList.remove('hidden');
    }
    
    // 更新其他玩家信息
    function updateOtherPlayers() {
      const players = gameData.currentRoom.players;
      const playerElements = ['player-top', 'player-left', 'player-right'];
      
      // 清空所有玩家信息
      playerElements.forEach(id => {
        const playerElement = document.getElementById(id);
        playerElement.querySelector('.player-avatar').src = '';
        playerElement.querySelector('.player-name').textContent = '';
        playerElement.querySelector('.player-chips').textContent = '';
        playerElement.querySelector('.player-status').textContent = '';
      });
      
      // 更新其他玩家信息
      let playerIndex = 0;
      for (let i = 0; i < players.length; i++) {
        const player = players[i];
        if (player.id === gameData.player.id) continue;
        
        if (playerIndex < playerElements.length) {
          const playerElement = document.getElementById(playerElements[playerIndex]);
          playerElement.querySelector('.player-avatar').src = player.avatar;
          playerElement.querySelector('.player-name').textContent = player.name;
          playerElement.querySelector('.player-chips').textContent = player.chips + ' chips';
          playerElement.querySelector('.player-status').textContent = player.status === 'ready' ? '已准备' : '准备中';
          
          playerIndex++;
        }
      }
    }
    
    // 模拟其他玩家加入
    function simulatePlayersJoining() {
      if (!gameData.currentRoom || gameData.currentRoom.status !== 'waiting') return;
      
      const aiAvatars = [
        'https://p3-doubao-search-sign.byteimg.com/mosaic-legacy/bdb0001864252078341~tplv-be4g95zd3a-image.jpeg?rk3s=1388297f&x-expires=1765011357&x-signature=7HCRLWAobymB9mZ5t3vN8YrXkE4%3D',
        'https://p3-doubao-search-sign.byteimg.com/mosaic-legacy/bdb0001864252078342~tplv-be4g95zd3a-image.jpeg?rk3s=1388297f&x-expires=1765011357&x-signature=k3H%2F8I7G9F3D2S1A4Q5W6E8R9T%3D',
        'https://p3-doubao-search-sign.byteimg.com/pgc-image/3732999201414056124521~tplv-be4g95zd3a-image.jpeg?rk3s=1388297f&x-expires=1765011357&x-signature=6G5F4D3S2A1Q8W7E9R6T5Y4U%3D'
      ];
      
      // 随机添加1-2个AI玩家
      const numAiPlayers = Math.floor(Math.random() * 2) + 1;
      const maxPlayers = 4;
      
      for (let i = 0; i < numAiPlayers; i++) {
        if (gameData.currentRoom.players.length >= maxPlayers) break;
        
        const aiPlayer = {
          id: 'ai-' + Date.now() + '-' + i,
          name: 'AI玩家' + (i + 1),
          avatar: aiAvatars[i % aiAvatars.length],
          chips: 1000,
          status: Math.random() > 0.5 ? 'ready' : 'waiting',
          isAi: true
        };
        
        gameData.currentRoom.players.push(aiPlayer);
        
        // 发送聊天消息
        if (Math.random() > 0.5) {
          setTimeout(() => {
            sendChatMessage(aiPlayer.name, aiPlayer.avatar, getRandomChatMessage());
          }, 1000 * (i + 1));
        }
      }
      
      // 更新玩家数量显示
      currentPlayerCount.textContent = gameData.currentRoom.players.length + '/4';
      
      // 更新其他玩家信息
      updateOtherPlayers();
      
      // 检查是否所有玩家都已准备
      checkAllPlayersReady();
    }
    
    // 获取随机聊天消息
    function getRandomChatMessage() {
      const messages = [
        '大家好！',
        '准备开始吧！',
        '我是新手，请多指教',
        '今天运气不错',
        '这局我一定会赢',
        '哈哈哈',
        '加油！'
      ];
      
      return messages[Math.floor(Math.random() * messages.length)];
    }
    
    // 切换准备状态
    function toggleReady() {
      if (!gameData.currentRoom || gameData.currentRoom.status !== 'waiting') return;
      
      const player = gameData.currentRoom.players.find(p => p.id === gameData.player.id);
      if (!player) return;
      
      player.status = player.status === 'ready' ? 'waiting' : 'ready';
      selfStatus.textContent = player.status === 'ready' ? '已准备' : '准备中';
      
      if (player.status === 'ready') {
        readyBtn.textContent = '取消准备';
        readyBtn.classList.remove('btn-accent');
        readyBtn.classList.add('btn-danger');
        
        // 发送聊天消息
        sendChatMessage(gameData.player.name, gameData.player.avatar, '我已准备好！');
      } else {
        readyBtn.textContent = '准备';
        readyBtn.classList.remove('btn-danger');
        readyBtn.classList.add('btn-accent');
      }
      
      // 检查是否所有玩家都已准备
      checkAllPlayersReady();
    }
    
    // 检查是否所有玩家都已准备
    function checkAllPlayersReady() {
      if (!gameData.currentRoom || gameData.currentRoom.status !== 'waiting') return;
      
      const readyPlayers = gameData.currentRoom.players.filter(p => p.status === 'ready');
      
      if (readyPlayers.length >= 2 && readyPlayers.length === gameData.currentRoom.players.length) {
        // 所有玩家都已准备，开始游戏
        gameMessage.textContent = '所有玩家已准备，游戏即将开始...';
        
        setTimeout(() => {
          startGame();
        }, 2000);
      } else {
        gameMessage.textContent = `等待其他玩家准备... (${readyPlayers.length}/${gameData.currentRoom.players.length})`;
      }
    }
    
    // 开始游戏
    function startGame() {
      if (!gameData.currentRoom) return;
      
      // 更新游戏状态
      gameData.currentRoom.status = 'playing';
      gameStatus.textContent = '游戏进行中';
      gameMessage.textContent = '游戏开始！';
      
      // 重置玩家状态
      gameData.currentRoom.players.forEach(player => {
        player.status = 'playing';
        player.cards = [];
        player.handRank = null;
        player.currentBet = 0;
      });
      
      // 更新自己的状态
      selfStatus.textContent = '游戏中';
      
      // 更新其他玩家状态
      updateOtherPlayers();
      
      // 创建牌堆
      createDeck();
      
      // 洗牌
      shuffleDeck();
      
      // 发牌
      dealCards();
      
      // 开始下注回合
      startBettingRound();
    }
    
    // 创建牌堆
    function createDeck() {
      const deck = [];
      
      for (const suit of suits) {
        for (const rank of ranks) {
          deck.push({
            suit: suit,
            rank: rank,
            value: cardValues[rank]
          });
        }
      }
      
      gameData.currentRoom.deck = deck;
    }
    
    // 洗牌
    function shuffleDeck() {
      const deck = gameData.currentRoom.deck;
      
      // Fisher-Yates 洗牌算法
      for (let i = deck.length - 1; i > 0; i--) {
        const j = Math.floor(Math.random() * (i + 1));
        [deck[i], deck[j]] = [deck[j], deck[i]];
      }
    }
    
    // 发牌
    function dealCards() {
      const players = gameData.currentRoom.players;
      const deck = gameData.currentRoom.deck;
      
      // 每位玩家发3张牌
      for (let i = 0; i < 3; i++) {
        for (const player of players) {
          const card = deck.pop();
          player.cards.push(card);
        }
      }
      
      // 显示自己的牌
      showSelfCards();
      
      // 分析自己的牌型
      analyzeHand();
    }
    
    // 显示自己的牌
    function showSelfCards() {
      selfCards.innerHTML = '';
      
      const player = gameData.currentRoom.players.find(p => p.id === gameData.player.id);
      if (!player || !player.cards) return;
      
      player.cards.forEach((card, index) => {
        const cardElement = document.createElement('div');
        cardElement.className = 'card animate-deal-card';
        cardElement.style.animationDelay = index * 0.2 + 's';
        
        const suitClass = getSuitClass(card.suit);
        
        cardElement.innerHTML = `
          <div class="card-front">
            <div class="card-rank ${suitClass}">${card.rank}</div>
            <div class="card-suit ${suitClass}">${card.suit}</div>
          </div>
        `;
        
        selfCards.appendChild(cardElement);
      });
    }
    
    // 获取花色对应的CSS类
    function getSuitClass(suit) {
      switch (suit) {
        case '♥': return 'suit-heart';
        case '♦': return 'suit-diamond';
        case '♣': return 'suit-club';
        case '♠': return 'suit-spade';
        default: return '';
      }
    }
    
    // 分析牌型
    function analyzeHand() {
      const player = gameData.currentRoom.players.find(p => p.id === gameData.player.id);
      if (!player || !player.cards || player.cards.length < 3) return;
      
      const cards = player.cards;
      
      // 排序牌
      cards.sort((a, b) => b.value - a.value);
      
      // 检查是否为豹子
      if (cards[0].rank === cards[1].rank && cards[1].rank === cards[2].rank) {
        player.handRank = { name: '豹子', value: 7, highCard: cards[0].value };
      }
      // 检查是否为顺金
      else if (isFlush(cards) && isStraight(cards)) {
        player.handRank = { name: '顺金', value: 6, highCard: cards[0].value };
      }
      // 检查是否为金花
      else if (isFlush(cards)) {
        player.handRank = { name: '金花', value: 5, highCard: cards[0].value };
      }
      // 检查是否为顺子
      else if (isStraight(cards)) {
        player.handRank = { name: '顺子', value: 4, highCard: cards[0].value };
      }
      // 检查是否为对子
      else if (cards[0].rank === cards[1].rank || cards[1].rank === cards[2].rank) {
        const pairValue = cards[0].rank === cards[1].rank ? cards[0].value : cards[1].value;
        const highCard = cards[0].rank === cards[1].rank ? cards[2].value : cards[0].value;
        player.handRank = { name: '对子', value: 3, pairValue: pairValue, highCard: highCard };
      }
      // 单张
      else {
        player.handRank = { name: '单张', value: 2, highCard: cards[0].value };
      }
      
      // 更新牌型显示
      handRank.textContent = '你的牌型: ' + player.handRank.name;
    }
    
    // 检查是否为同花
    function isFlush(cards) {
      return cards[0].suit === cards[1].suit && cards[1].suit === cards[2].suit;
    }
    
    // 检查是否为顺子
    function isStraight(cards) {
      // 特殊情况：A-2-3
      if (cards[0].value === 14 && cards[1].value === 3 && cards[2].value === 2) {
        return true;
      }
      
      // 普通顺子
      return cards[0].value - cards[1].value === 1 && cards[1].value - cards[2].value === 1;
    }
    
    // 开始下注回合
    function startBettingRound() {
      if (!gameData.currentRoom) return;
      
      // 重置当前回合
      gameData.currentRoom.currentTurn = 0;
      gameData.currentRoom.pot = 0;
      potAmount.textContent = '0 chips';
      
      // 强制下注（底注）
      const smallBlind = 10;
      const bigBlind = 20;
      
      // 小盲注
      const smallBlindPlayer = gameData.currentRoom.players[0];
      smallBlindPlayer.chips = Math.max(0, smallBlindPlayer.chips - smallBlind);
      smallBlindPlayer.currentBet = smallBlind;
      gameData.currentRoom.pot += smallBlind;
      
      // 大盲注
      const bigBlindPlayer = gameData.currentRoom.players.length > 1 ? gameData.currentRoom.players[1] : smallBlindPlayer;
      bigBlindPlayer.chips = Math.max(0, bigBlindPlayer.chips - bigBlind);
      bigBlindPlayer.currentBet = bigBlind;
      gameData.currentRoom.pot += bigBlind;
      
      // 更新底注显示
      potAmount.textContent = gameData.currentRoom.pot + ' chips';
      
      // 更新玩家筹码显示
      updatePlayerChips();
      
      // 开始第一轮下注
      startNextTurn();
    }
    
    // 更新玩家筹码显示
    function updatePlayerChips() {
      // 更新自己的筹码
      selfChips.textContent = gameData.player.chips + ' chips';
      
      // 更新其他玩家的筹码
      const players = gameData.currentRoom.players;
      const playerElements = ['player-top', 'player-left', 'player-right'];
      
      let playerIndex = 0;
      for (let i = 0; i < players.length; i++) {
        const player = players[i];
        if (player.id === gameData.player.id) continue;
        
        if (playerIndex < playerElements.length) {
          const playerElement = document.getElementById(playerElements[playerIndex]);
          playerElement.querySelector('.player-chips').textContent = player.chips + ' chips';
          
          playerIndex++;
        }
      }
    }
    
    // 开始下一个回合
    function startNextTurn() {
      if (!gameData.currentRoom) return;
      
      const players = gameData.currentRoom.players;
      let currentPlayerIndex = gameData.currentRoom.currentTurn;
      
      // 找到下一个还在游戏中的玩家
      while (true) {
        currentPlayerIndex = (currentPlayerIndex + 1) % players.length;
        
        if (players[currentPlayerIndex].status === 'playing') {
          gameData.currentRoom.currentTurn = currentPlayerIndex;
          break;
        }
        
        // 检查是否所有玩家都已弃牌
        const activePlayers = players.filter(p => p.status === 'playing');
        if (activePlayers.length <= 1) {
          // 只有一名玩家 remaining，结束下注回合
          endBettingRound();
          return;
        }
      }
      
      const currentPlayer = players[currentPlayerIndex];
      
      // 更新当前回合显示
      currentTurn.textContent = currentPlayer.name;
      
      // 检查是否为自己的回合
      if (currentPlayer.id === gameData.player.id) {
        // 自己的回合，启用按钮
        gameMessage.textContent = '轮到你行动';
        foldBtn.disabled = false;
        checkBtn.disabled = false;
        betMinus.disabled = false;
        betPlus.disabled = false;
        betAmount.disabled = false;
        betBtn.disabled = false;
        
        // 设置最小下注金额
        const minBet = 10;
        betAmount.min = minBet;
        betAmount.value = minBet;
      } else {
        // AI玩家的回合，禁用按钮
        gameMessage.textContent = '等待 ' + currentPlayer.name + ' 行动...';
        foldBtn.disabled = true;
        checkBtn.disabled = true;
        betMinus.disabled = true;
        betPlus.disabled = true;
        betAmount.disabled = true;
        betBtn.disabled = true;
        
        // 如果是AI玩家，模拟行动
        if (currentPlayer.isAi) {
          setTimeout(() => {
            simulateAiAction(currentPlayer);
          }, 1500);
        }
      }
    }
    
    // 模拟AI行动
    function simulateAiAction(player) {
      if (!gameData.currentRoom) return;
      
      // 分析AI的牌型
      const cards = player.cards;
      cards.sort((a, b) => b.value - a.value);
      
      let handRankValue = 1; // 默认高牌
      
      // 检查是否为豹子
      if (cards[0].rank === cards[1].rank && cards[1].rank === cards[2].rank) {
        handRankValue = 7;
      }
      // 检查是否为顺金
      else if (isFlush(cards) && isStraight(cards)) {
        handRankValue = 6;
      }
      // 检查是否为金花
      else if (isFlush(cards)) {
        handRankValue = 5;
      }
      // 检查是否为顺子
      else if (isStraight(cards)) {
        handRankValue = 4;
      }
      // 检查是否为对子
      else if (cards[0].rank === cards[1].rank || cards[1].rank === cards[2].rank) {
        handRankValue = 3;
      }
      // 单张
      else if (cards[0].value >= 12) { // J以上
        handRankValue = 2;
      }
      
      // 根据牌型决定行动
      const rand = Math.random();
      let action = '';
      let betAmount = 0;
      
      if (handRankValue >= 6) { // 豹子或顺金
        // 90%概率加注
        if (rand < 0.9) {
          action = 'raise';
          betAmount = Math.min(player.chips, 50 + Math.floor(Math.random() * 50));
        } else {
          action = 'check';
        }
      } else if (handRankValue >= 4) { // 金花或顺子
        // 70%概率加注，20%概率跟注，10%概率弃牌
        if (rand < 0.7) {
          action = 'raise';
          betAmount = Math.min(player.chips, 30 + Math.floor(Math.random() * 30));
        } else if (rand < 0.9) {
          action = 'check';
        } else {
          action = 'fold';
        }
      } else if (handRankValue >= 3) { // 对子
        // 50%概率跟注，30%概率弃牌，20%概率加注
        if (rand < 0.5) {
          action = 'check';
        } else if (rand < 0.8) {
          action = 'fold';
        } else {
          action = 'raise';
          betAmount = Math.min(player.chips, 20 + Math.floor(Math.random() * 20));
        }
      } else { // 单张或高牌
        // 60%概率弃牌，30%概率跟注，10%概率加注
        if (rand < 0.6) {
          action = 'fold';
        } else if (rand < 0.9) {
          action = 'check';
        } else {
          action = 'raise';
          betAmount = Math.min(player.chips, 10 + Math.floor(Math.random() * 10));
        }
      }
      
      // 执行行动
      setTimeout(() => {
        if (action === 'fold') {
          // 弃牌
          player.status = 'folded';
          gameMessage.textContent = player.name + ' 弃牌';
          
          // 更新玩家状态
          updateOtherPlayers();
          
          // 发送聊天消息
          if (Math.random() > 0.7) {
            sendChatMessage(player.name, player.avatar, getRandomFoldMessage());
          }
        } else if (action === 'check') {
          // 过牌
          gameMessage.textContent = player.name + ' 过牌';
          
          // 发送聊天消息
          if (Math.random() > 0.7) {
            sendChatMessage(player.name, player.avatar, getRandomCheckMessage());
          }
        } else if (action === 'raise') {
          // 下注
          if (betAmount > 0) {
            player.chips = Math.max(0, player.chips - betAmount);
            player.currentBet = (player.currentBet || 0) + betAmount;
            gameData.currentRoom.pot += betAmount;
            
            // 更新奖池显示
            potAmount.textContent = gameData.currentRoom.pot + ' chips';
            
            // 更新玩家筹码显示
            updatePlayerChips();
            
            gameMessage.textContent = player.name + ' 下注 ' + betAmount + ' chips';
            
            // 发送聊天消息
            if (Math.random() > 0.7) {
              sendChatMessage(player.name, player.avatar, getRandomBetMessage(betAmount));
            }
          } else {
            // 过牌
            gameMessage.textContent = player.name + ' 过牌';
          }
        }
        
        // 继续下一个回合
        startNextTurn();
      }, 1000);
    }
    
    // 获取随机弃牌消息
    function getRandomFoldMessage() {
      const messages = [
        '这牌不行，弃了',
        '下次好运',
        '你们玩',
        '溜了溜了'
      ];
      
      return messages[Math.floor(Math.random() * messages.length)];
    }
    
    // 获取随机过牌消息
    function getRandomCheckMessage() {
      const messages = [
        '过牌',
        '看看再说',
        '谨慎一点',
        '不急'
      ];
      
      return messages[Math.floor(Math.random() * messages.length)];
    }
    
    // 获取随机下注消息
    function getRandomBetMessage(amount) {
      const messages = [
        '加注 ' + amount + '!',
        '这牌我有信心',
        '跟注',
        '看看谁才是赢家'
      ];
      
      return messages[Math.floor(Math.random() * messages.length)];
    }
    
    // 弃牌
    function fold() {
      if (!gameData.currentRoom) return;
      
      const player = gameData.currentRoom.players.find(p => p.id === gameData.player.id);
      if (!player || player.status !== 'playing') return;
      
      // 更新玩家状态
      player.status = 'folded';
      selfStatus.textContent = '已弃牌';
      
      // 发送聊天消息
      sendChatMessage(gameData.player.name, gameData.player.avatar, '我弃牌了');
      
      // 禁用按钮
      foldBtn.disabled = true;
      checkBtn.disabled = true;
      betMinus.disabled = true;
      betPlus.disabled = true;
      betAmount.disabled = true;
      betBtn.disabled = true;
      
      // 继续下一个回合
      startNextTurn();
    }
    
    // 过牌
    function check() {
      if (!gameData.currentRoom) return;
      
      const player = gameData.currentRoom.players.find(p => p.id === gameData.player.id);
      if (!player || player.status !== 'playing') return;
      
      // 发送聊天消息
      sendChatMessage(gameData.player.name, gameData.player.avatar, '我过牌');
      
      // 禁用按钮
      foldBtn.disabled = true;
      checkBtn.disabled = true;
      betMinus.disabled = true;
      betPlus.disabled = true;
      betAmount.disabled = true;
      betBtn.disabled = true;
      
      // 继续下一个回合
      startNextTurn();
    }
    
    // 改变下注金额
    function changeBetAmount(change) {
      const currentValue = parseInt(betAmount.value);
      const minValue = parseInt(betAmount.min);
      const maxValue = gameData.player.chips;
      
      let newValue = currentValue + change;
      newValue = Math.max(minValue, Math.min(maxValue, newValue));
      
      betAmount.value = newValue;
    }
    
    // 下注
    function bet() {
      if (!gameData.currentRoom) return;
      
      const player = gameData.currentRoom.players.find(p => p.id === gameData.player.id);
      if (!player || player.status !== 'playing') return;
      
      const amount = parseInt(betAmount.value);
      
      if (amount <= 0 || amount > player.chips) {
        alert('下注金额无效');
        return;
      }
      
      // 更新玩家筹码和下注
      player.chips = Math.max(0, player.chips - amount);
      player.currentBet = (player.currentBet || 0) + amount;
      gameData.currentRoom.pot += amount;
      
      // 更新奖池显示
      potAmount.textContent = gameData.currentRoom.pot + ' chips';
      
      // 更新自己的筹码显示
      selfChips.textContent = player.chips + ' chips';
      
      // 发送聊天消息
      sendChatMessage(gameData.player.name, gameData.player.avatar, '我下注 ' + amount + ' chips');
      
      // 禁用按钮
      foldBtn.disabled = true;
      checkBtn.disabled = true;
      betMinus.disabled = true;
      betPlus.disabled = true;
      betAmount.disabled = true;
      betBtn.disabled = true;
      
      // 继续下一个回合
      startNextTurn();
    }
    
    // 结束下注回合
    function endBettingRound() {
      if (!gameData.currentRoom) return;
      
      gameMessage.textContent = '下注结束，摊牌！';
      
      // 显示所有玩家的牌
      showAllPlayersCards();
      
      // 分析所有玩家的牌型
      analyzeAllHands();
      
      // 比较牌型，决定胜负
      setTimeout(() => {
        determineWinner();
      }, 3000);
    }
    
    // 显示所有玩家的牌
    function showAllPlayersCards() {
      const players = gameData.currentRoom.players;
      const playerElements = ['player-top', 'player-left', 'player-right'];
      
      let playerIndex = 0;
      for (let i = 0; i < players.length; i++) {
        const player = players[i];
        if (player.id === gameData.player.id) continue;
        
        if (playerIndex < playerElements.length) {
          const playerElement = document.getElementById(playerElements[playerIndex]);
          const cardsElement = playerElement.querySelector('.player-cards');
          
          cardsElement.innerHTML = '';
          
          if (player.status === 'playing' || player.status === 'folded') {
            player.cards.forEach((card, index) => {
              const cardElement = document.createElement('div');
              cardElement.className = 'card animate-deal-card';
              cardElement.style.animationDelay = index * 0.2 + 's';
              
              const suitClass = getSuitClass(card.suit);
              
              cardElement.innerHTML = `
                <div class="card-front">
                  <div class="card-rank ${suitClass}">${card.rank}</div>
                  <div class="card-suit ${suitClass}">${card.suit}</div>
                </div>
              `;
              
              cardsElement.appendChild(cardElement);
            });
          }
          
          playerIndex++;
        }
      }
    }
    
    // 分析所有玩家的牌型
    function analyzeAllHands() {
      const players = gameData.currentRoom.players;
      
      for (const player of players) {
        if (player.status !== 'playing') continue;
        
        const cards = player.cards;
        cards.sort((a, b) => b.value - a.value);
        
        // 检查是否为豹子
        if (cards[0].rank === cards[1].rank && cards[1].rank === cards[2].rank) {
          player.handRank = { name: '豹子', value: 7, highCard: cards[0].value };
        }
        // 检查是否为顺金
        else if (isFlush(cards) && isStraight(cards)) {
          player.handRank = { name: '顺金', value: 6, highCard: cards[0].value };
        }
        // 检查是否为金花
        else if (isFlush(cards)) {
          player.handRank = { name: '金花', value: 5, highCard: cards[0].value };
        }
        // 检查是否为顺子
        else if (isStraight(cards)) {
          player.handRank = { name: '顺子', value: 4, highCard: cards[0].value };
        }
        // 检查是否为对子
        else if (cards[0].rank === cards[1].rank || cards[1].rank === cards[2].rank) {
          const pairValue = cards[0].rank === cards[1].rank ? cards[0].value : cards[1].value;
          const highCard = cards[0].rank === cards[1].rank ? cards[2].value : cards[0].value;
          player.handRank = { name: '对子', value: 3, pairValue: pairValue, highCard: highCard };
        }
        // 单张
        else {
          player.handRank = { name: '单张', value: 2, highCard: cards[0].value };
        }
      }
    }
    
    // 决定胜负
    function determineWinner() {
      if (!gameData.currentRoom) return;
      
      const players = gameData.currentRoom.players;
      const activePlayers = players.filter(p => p.status === 'playing');
      
      // 如果只有一名玩家 remaining，该玩家获胜
      if (activePlayers.length <= 1) {
        const winner = activePlayers[0] || players.find(p => p.status !== 'folded');
        
        if (winner) {
          winner.chips += gameData.currentRoom.pot;
          showResult([winner]);
        }
        
        return;
      }
      
      // 比较牌型，找出获胜者
      const sortedPlayers = [...activePlayers].sort((a, b) => {
        // 比较牌型大小
        if (a.handRank.value !== b.handRank.value) {
          return b.handRank.value - a.handRank.value;
        }
        
        // 牌型相同，比较高牌
        if (a.handRank.highCard !== b.handRank.highCard) {
          return b.handRank.highCard - a.handRank.highCard;
        }
        
        // 高牌相同，比较对子（如果有）
        if (a.handRank.pairValue && b.handRank.pairValue) {
          return b.handRank.pairValue - a.handRank.pairValue;
        }
        
        // 对子也相同，比较剩余牌
        for (let i = 0; i < 3; i++) {
          if (a.cards[i].value !== b.cards[i].value) {
            return b.cards[i].value - a.cards[i].value;
          }
        }
        
        // 完全相同，平局
        return 0;
      });
      
      // 找出所有获胜者（可能有平局）
      const winners = [sortedPlayers[0]];
      const highestRank = sortedPlayers[0].handRank.value;
      const highestHighCard = sortedPlayers[0].handRank.highCard;
      const highestPairValue = sortedPlayers[0].handRank.pairValue || 0;
      
      for (let i = 1; i < sortedPlayers.length; i++) {
        const player = sortedPlayers[i];
        
        if (player.handRank.value !== highestRank) break;
        if (player.handRank.highCard !== highestHighCard) break;
        if ((player.handRank.pairValue || 0) !== highestPairValue) break;
        
        winners.push(player);
      }
      
      // 分配奖金
      const potPerWinner = Math.floor(gameData.currentRoom.pot / winners.length);
      const remainder = gameData.currentRoom.pot % winners.length;
      
      winners.forEach((winner, index) => {
        winner.chips += potPerWinner;
        if (index === 0) winner.chips += remainder;
      });
      
      // 显示结果
      showResult(winners);
    }
    
    // 显示结果
    function showResult(winners) {
      if (!gameData.currentRoom) return;
      
      // 更新玩家筹码显示
      updatePlayerChips();
      
      // 高亮显示获胜者
      highlightWinners(winners);
      
      // 准备结果内容
      resultContent.innerHTML = '';
      
      // 添加奖池信息
      const potElement = document.createElement('div');
      potElement.className = 'text-center mb-4';
      potElement.innerHTML = `<h4 class="text-xl font-bold text-accent">奖池: ${gameData.currentRoom.pot} chips</h4>`;
      resultContent.appendChild(potElement);
      
      // 添加获胜者信息
      const winnersElement = document.createElement('div');
      winnersElement.className = 'space-y-4';
      
      if (winners.length === 1) {
        const winner = winners[0];
        
        winnersElement.innerHTML += `
          <div class="flex items-center justify-center">
            <img src="${winner.avatar}" alt="${winner.name}" class="w-12 h-12 rounded-full mr-3">
            <div>
              <div class="font-medium">${winner.name} 获胜！</div>
              <div class="text-sm text-gray-300">牌型: ${winner.handRank ? winner.handRank.name : '无'}</div>
            </div>
          </div>
        `;
      } else {
        winnersElement.innerHTML += `<div class="text-center mb-2">平局！</div>`;
        
        winners.forEach(winner => {
          winnersElement.innerHTML += `
            <div class="flex items-center justify-center">
              <img src="${winner.avatar}" alt="${winner.name}" class="w-10 h-10 rounded-full mr-2">
              <div>
                <div>${winner.name}</div>
                <div class="text-xs text-gray-300">牌型: ${winner.handRank ? winner.handRank.name : '无'}</div>
              </div>
            </div>
          `;
        });
      }
      
      resultContent.appendChild(winnersElement);
      
      // 添加所有玩家的牌型信息
      const allPlayersElement = document.createElement('div');
      allPlayersElement.className = 'mt-6 space-y-2';
      allPlayersElement.innerHTML = '<h4 class="font-medium mb-2">所有玩家牌型:</h4>';
      
      gameData.currentRoom.players.forEach(player => {
        if (player.status === 'folded') {
          allPlayersElement.innerHTML += `
            <div class="flex items-center">
              <img src="${player.avatar}" alt="${player.name}" class="w-6 h-6 rounded-full mr-2">
              <div>${player.name}: 已弃牌</div>
            </div>
          `;
        } else {
          allPlayersElement.innerHTML += `
            <div class="flex items-center">
              <img src="${player.avatar}" alt="${player.name}" class="w-6 h-6 rounded-full mr-2">
              <div>${player.name}: ${player.handRank ? player.handRank.name : '无'}</div>
            </div>
          `;
        }
      });
      
      resultContent.appendChild(allPlayersElement);
      
      // 显示结果弹窗
      resultModal.classList.remove('hidden');
      
      // 发送聊天消息
      if (winners.some(w => w.id === gameData.player.id)) {
        sendChatMessage(gameData.player.name, gameData.player.avatar, '我赢了！');
      } else {
        sendChatMessage(gameData.player.name, gameData.player.avatar, '下次好运');
      }
    }
    
    // 高亮显示获胜者
    function highlightWinners(winners) {
      // 移除所有高亮
      document.querySelectorAll('.player-cards').forEach(cards => {
        cards.classList.remove('highlight-winner');
      });
      
      // 高亮自己
      if (winners.some(w => w.id === gameData.player.id)) {
        selfCards.classList.add('highlight-winner');
      }
      
      // 高亮其他获胜者
      const players = gameData.currentRoom.players;
      const playerElements = ['player-top', 'player-left', 'player-right'];
      
      let playerIndex = 0;
      for (let i = 0; i < players.length; i++) {
        const player = players[i];
        if (player.id === gameData.player.id) continue;
        
        if (playerIndex < playerElements.length) {
          const playerElement = document.getElementById(playerElements[playerIndex]);
          const cardsElement = playerElement.querySelector('.player-cards');
          
          if (winners.some(w => w.id === player.id)) {
            cardsElement.classList.add('highlight-winner');
          }
          
          playerIndex++;
        }
      }
    }
    
    // 开始新游戏
    function startNewGame() {
      // 隐藏结果弹窗
      resultModal.classList.add('hidden');
      
      // 重置游戏状态
      gameData.currentRoom.status = 'waiting';
      gameStatus.textContent = '等待玩家准备';
      
      // 重置玩家状态
      gameData.currentRoom.players.forEach(player => {
        player.status = 'waiting';
        player.cards = [];
        player.handRank = null;
        player.currentBet = 0;
      });
      
      // 更新自己的状态
      selfStatus.textContent = '准备中';
      
      // 更新其他玩家状态
      updateOtherPlayers();
      
      // 重置自己的牌
      selfCards.innerHTML = `
        <div class="player-card-slot"></div>
        <div class="player-card-slot"></div>
        <div class="player-card-slot"></div>
      `;
      
      // 重置其他玩家的牌
      document.querySelectorAll('.player-cards').forEach(cards => {
        if (cards.id !== 'self-cards') {
          cards.innerHTML = `
            <div class="card card-back"></div>
            <div class="card card-back"></div>
            <div class="card card-back"></div>
          `;
        }
      });
      
      // 重置按钮状态
      readyBtn.textContent = '准备';
      readyBtn.classList.remove('btn-danger');
      readyBtn.classList.add('btn-accent');
      foldBtn.disabled = true;
      checkBtn.disabled = true;
      betMinus.disabled = true;
      betPlus.disabled = true;
      betAmount.disabled = true;
      betBtn.disabled = true;
      
      // 重置游戏消息
      gameMessage.textContent = '等待其他玩家准备...';
      handRank.textContent = '你的牌型: -';
      
      // 模拟AI玩家准备
      setTimeout(() => {
        gameData.currentRoom.players.forEach(player => {
          if (player.isAi && Math.random() > 0.3) {
            player.status = 'ready';
            
            // 发送聊天消息
            if (Math.random() > 0.7) {
              sendChatMessage(player.name, player.avatar, '再来一局！');
            }
          }
        });
        
        // 更新其他玩家状态
        updateOtherPlayers();
        
        // 检查是否所有玩家都已准备
        checkAllPlayersReady();
      }, 1500);
    }
    
    // 发送聊天消息
    function sendChat() {
      const message = chatInput.value.trim();
      
      if (!message) return;
      
      sendChatMessage(gameData.player.name, gameData.player.avatar, message);
      
      // 清空输入框
      chatInput.value = '';
    }
    
    // 发送聊天消息（内部使用）
    function sendChatMessage(senderName, senderAvatar, message) {
      const chatMessage = {
        sender: senderName,
        avatar: senderAvatar,
        message: message,
        timestamp: new Date()
      };
      
      gameData.chatMessages.push(chatMessage);
      
      // 添加到聊天区域
      const messageElement = document.createElement('div');
      messageElement.className = 'flex items-start';
      messageElement.innerHTML = `
        <img src="${senderAvatar}" alt="${senderName}" class="w-6 h-6 rounded-full mr-2 mt-0.5">
        <div>
          <div class="flex items-center">
            <span class="text-xs font-medium">${senderName}</span>
            <span class="text-xs text-gray-400 ml-2">${formatTime(chatMessage.timestamp)}</span>
          </div>
          <p class="text-sm">${message}</p>
        </div>
      `;
      
      chatMessages.appendChild(messageElement);
      
      // 滚动到底部
      chatMessages.scrollTop = chatMessages.scrollHeight;
    }
    
    // 格式化时间
    function formatTime(date) {
      const hours = date.getHours().toString().padStart(2, '0');
      const minutes = date.getMinutes().toString().padStart(2, '0');
      
      return `${hours}:${minutes}`;
    }
    
    // 初始化游戏
    init();
  </script>
</body>
</html>
